package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.framework.interceptor.MyMetaObjectHandler;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.dto.ProcessingResultDto;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.mapper.NursingElderMapper;
import com.zzyl.system.mapper.SysUserMapper;
import com.zzyl.system.mapper.SysUserRoleMapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertDataMapper;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.service.IAlertDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 报警数据Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-05
 */
@Service
public class AlertDataServiceImpl extends ServiceImpl<AlertDataMapper, AlertData> implements IAlertDataService {
    @Autowired
    private AlertDataMapper alertDataMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    NursingElderMapper nursingElderMapper;
    @Autowired
    ElderMapper elderMapper;
    @Autowired
    SysUserRoleMapper sysUserRoleMapper;

    /**
     * 查询报警数据
     *
     * @param id 报警数据主键
     * @return 报警数据
     */
    @Override
    public AlertData selectAlertDataById(Long id) {
        return getById(id);
    }

    /**
     * 查询报警数据列表
     *
     * @param alertData 报警数据
     * @return 报警数据
     */
    @Override
    public List<AlertData> selectAlertDataList(AlertData alertData) {

        Long nowId = MyMetaObjectHandler.loadUserId();
        List<AlertData> data = alertDataMapper.selectAlertDataList(alertData);
        return data.stream().filter(item -> Objects.equals(nowId, item.getUserId())).collect(Collectors.toList());
    }

    /**
     * 新增报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int insertAlertData(AlertData alertData) {
        return save(alertData) ? 1 : 0;
    }

    /**
     * 修改报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int updateAlertData(AlertData alertData) {
        return updateById(alertData) ? 1 : 0;
    }

    /**
     * 批量删除报警数据
     *
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警数据信息
     *
     * @param id 报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Transactional
    @Override
    /**
     * 处理告警数据：更新当前告警状态，并同步关联护理员的告警数据
     * 设计思路：
     * 1. 老人未与管理员直接关联，通过Token获取当前操作用户（管理员）信息，先更新主告警数据
     * 2. 根据告警的设备类型（随身/固定），通过不同维度获取老人ID（随身设备直接关联老人，固定设备通过床位关联老人）
     * 3. 因护理员与老人是多对多关系，无法通过护理员ID反向查老人，先查老人ID再关联护理员ID
     * 4. 遍历护理员ID，同步更新每个护理员对应的告警数据，确保操作人信息统一为当前管理员
     *
     * @param processingResultDto 告警处理结果DTO：包含告警ID、处理时间、处理结果等前端传递的核心数据
     */
    /**
     * 处理告警数据：更新主告警记录状态，并同步关联护理员的告警信息
     */
    public void handleAlertData(ProcessingResultDto processingResultDto) {
        // 查询当前要处理的告警数据（保留原始数据用于后续判断）
        AlertData nowAlertData = alertDataMapper.selectAlertDataById(processingResultDto.getId());
        AlertData alertData = alertDataMapper.selectAlertDataById(processingResultDto.getId());

        // 从token获取当前操作用户（管理员）信息
        Long currentOperatorId = SecurityUtils.getUserId();
        SysUser currentOperator = sysUserMapper.selectUserById(currentOperatorId);
        LocalDateTime creatTime = alertDataMapper.selectCreatTimeByid(processingResultDto.getId());
        if (creatTime != null) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedTime = creatTime.format(formatter);
            // 使用 formattedTime 进行后续操作
        }

        // 1. 更新主告警数据：复制处理结果，设置状态和处理人
        BeanUtils.copyProperties(processingResultDto, nowAlertData);
        // 标记为已处理
        nowAlertData.setStatus(1);
        nowAlertData.setProcessorId(currentOperatorId);
        nowAlertData.setProcessorName(currentOperator.getNickName());
        String iotId = alertData.getIotId();
        String functionId = alertData.getFunctionId();
        alertDataMapper.updateAlertData(nowAlertData);

        // 2. 同步护理员的告警数据（根据设备类型关联老人，再查护理员）
        // 位置类型为1（需关联老人的设备）
        if (alertData.getLocationType() == 1) {
            // 物理位置类型为2（固定设备：通过床位查老人）
            if (alertData.getPhysicalLocationType() == 2) {
                // 固定设备->床位ID->老人信息
                Elder elder = elderMapper.selectElderByBedId(alertData.getAccessLocation());
                // 老人ID->关联的护理员ID列表（解决多对多反向查询问题）
                updateOtherNursingData(processingResultDto, elder, currentOperatorId, currentOperator,iotId,functionId,creatTime);
            }
            else {
               List<Long> ids = sysUserRoleMapper.selectRoleIdByUserId();
               ids.forEach(
                       userId -> {
                           AlertData staffAlert = alertDataMapper.selectAlertDataByUserId(userId, iotId, functionId, creatTime);
                           staffAlert.setProcessingTime(processingResultDto.getProcessingTime());
                           staffAlert.setProcessingResult(processingResultDto.getProcessingResult());
                           staffAlert.setProcessorId(currentOperatorId);
                           staffAlert.setStatus(1);
                           staffAlert.setProcessorName(currentOperator.getNickName());
                           alertDataMapper.updateAlertData(staffAlert);
                       }
               );

            }
        }else {
            Elder elder = elderMapper.selectElderById(Long.valueOf(alertData.getAccessLocation()));
            updateOtherNursingData(processingResultDto, elder, currentOperatorId, currentOperator, iotId, functionId,creatTime);
        }
        if (!(currentOperatorId == 1)){
            AlertData adminData = alertDataMapper.selectAlertDataByUserId(1L, iotId, functionId, creatTime);
            adminData.setProcessingTime(processingResultDto.getProcessingTime());
            adminData.setProcessingResult(processingResultDto.getProcessingResult());
            adminData.setStatus(1);
            adminData.setProcessorId(currentOperatorId);
            adminData.setProcessorName(currentOperator.getNickName());
            alertDataMapper.updateAlertData(adminData);
        }
    }    /**/

    private void updateOtherNursingData(ProcessingResultDto processingResultDto, Elder elder, Long currentOperatorId, SysUser currentOperator, String iotId, String functionId, LocalDateTime creatTime) {
        List<Long> nursingStaffIds = nursingElderMapper.selectUserIdsByElderId(elder.getId());

        // 遍历护理员，同步更新其告警数据（处理信息与主告警一致，处理人为当前管理员）
        nursingStaffIds.forEach(userId -> {
            AlertData staffAlert = alertDataMapper.selectAlertDataByUserId(userId, iotId, functionId, creatTime);
            staffAlert.setProcessingTime(processingResultDto.getProcessingTime());
            staffAlert.setProcessingResult(processingResultDto.getProcessingResult());
            staffAlert.setStatus(1);
            staffAlert.setProcessorId(currentOperatorId);
            staffAlert.setProcessorName(currentOperator.getNickName());
            alertDataMapper.updateAlertData(staffAlert);
        });
    }


}
